import React, {Component} from 'react'
import {routerShape} from 'react-router';
import {inject, observer} from 'mobx-react';
import {observable, action, toJS} from 'mobx';
import {Spin, message, Modal, Button, Icon,Select} from 'antd';

import '../../../../style/myBlog/rightContainer/weibo.less'

import {WeaDropdown, WeaRichText,WeaBrowser,WeaHelpfulTip} from 'ecCom'

import WeiboBar from "./WeiboBar"

import ComVar from "../ComVar"

const {PublicRangeType, ComeFrom} = ComVar

import WeaUtils from "../../../Component/wea-utils"

const {DateFormat} = WeaUtils

import Mood from "./Mood"
import "./WeiboEdit.less"

import * as Util from '../../../../util/index'
import Dict from '../../../Component/wea-blog-dict';

import {WeaLocaleProvider} from "ecCom";
import WeiboEcmeEdit from "./WeiboEcmeEdit";

const { Option } = Select;


const getLabel = WeaLocaleProvider.getLabel;
const mirror = Dict.bottomBarMirror;
const confirm = Modal.confirm;
@inject('blogMyBlog')
@observer

class WeiboEdit extends Component {
  static contextTypes = {
    router: routerShape
  }

  constructor(props) {
    super(props);
    this.state = {
      editing: false,
      authType: PublicRangeType.public,
      authRange: [],
      mood: "1",
      status: '',
      richValue: '',
      isFirstIn: true, //fix:默认数据不能删掉问题
      caogao:'',
      ecmeTemplateid:"",
      viewShareType:'1',
      shareValue:'',
      sreplaceDatas:[],
      showBdShare:0
    }
    this.CKE_ID = `wea_ckeditor_weibo_${props.blogType}_edit`;
    this.onTempletChange = this.onTempletChange.bind(this);
  }

  componentDidMount() {
   const {getNote} = this.props.blogMyBlog;
    getNote({},false,(res) => {
      if(res.bdshare==1){
          this.setState({showBdShare:1})
      }
       if(res.notetiming==1&&res.notetime>0){
           this.interval = setInterval(() => this.autoSaveBlog(), res.notetime);
       }
    });
  }

  componentWillReceiveProps(nextProps) {
    const {defaultTemplate} = this.props;
    if (!nextProps.hasSubmited && defaultTemplate && defaultTemplate.tempContent && nextProps.defaultTemplate && nextProps.defaultTemplate.tempContent && defaultTemplate.tempContent !== nextProps.defaultTemplate.tempContent) {
      this.setState({richValue: nextProps.defaultTemplate.tempContent});
    }

  }
  
   blognottt = () =>{
      let {changeBqVisDiaLog,getNote} = this.props.blogMyBlog
      changeBqVisDiaLog(true);
	  getNote();
  }



  autoSaveBlog = () => {
      let {saveNote,changeCaoGao,caogao} = this.props.blogMyBlog;
      let ckref = this.refs[this.CKE_ID];
      if (this.refs[this.CKE_ID] && this.refs[this.CKE_ID].wrappedInstance) {
          ckref = this.refs[this.CKE_ID].wrappedInstance;
      }
      if (!(ckref && ckref.checkMode())) {
          message.error(getLabel('384536', "不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式"));
          return;
      }

      let value = ckref.getData();
      if(caogao.length!=value.length){
          changeCaoGao(value);
          saveNote({workdate:DateFormat(new Date(), "yyyy-MM-dd"),content:value},false,true);
      }else if(caogao!=value){
          changeCaoGao(value);
          saveNote({workdate:DateFormat(new Date(), "yyyy-MM-dd"),content:value},false,true);
      }
  }

  saveBlog = () => {
      let {saveNote,changeCaoGao} = this.props.blogMyBlog;
      let ckref = this.refs[this.CKE_ID];
      if (this.refs[this.CKE_ID] && this.refs[this.CKE_ID].wrappedInstance) {
          ckref = this.refs[this.CKE_ID].wrappedInstance;
      }
      if (!(ckref && ckref.checkMode())) {
          message.error(getLabel('384536', "不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式"));
          return;
      }
      let value = ckref.getData();

          changeCaoGao(value);
          saveNote({workdate:DateFormat(new Date(), "yyyy-MM-dd"),content:value});


  }




    componentWillUnmount(){
        clearInterval(this.interval);
    }

    onStausChange = (s) => {

        this.setState({status:s})
        let {getNote} = this.props.blogMyBlog;
        if(getNote){
            getNote({workdate:DateFormat(new Date(), "yyyy-MM-dd")},(res) => {
                this.setState({richValue: res});
            });
        }

    }

    onSelect = (key, data) => {

    }



    changeShowViewShare = (e) => {
        e.nativeEvent.stopImmediatePropagation();
        const {workdate } = this.props;
        let vid =  "#shareFirstDiv_"+workdate;
        let shareDivCss =  jQuery(vid).css("display")
        if(shareDivCss=='block'){
            jQuery(vid).css("display","none")
        }else{
            jQuery(vid).css("display","block")
        }

    }

    changeviewShareType = (val,ids) => {

        const {workdate} = this.props;
        const {changeReplaceDatas} = this.props.blogMyBlog;
        changeReplaceDatas([])


      if(ids!=undefined&&ids!=''){
          let vid =  "#shareFirstDiv_"+workdate;
          jQuery(vid).css("display","none")
          this.setState({viewShareType:val+"",shareValue:ids,sreplaceDatas:[]})
      }else if(ids!=undefined&&ids==''){
          this.setState({viewShareType:1+"",sreplaceDatas:[]})
      }else {
          this.setState({viewShareType:val+"",sreplaceDatas:[]})
      }

    }


    changeviewShareTypeDis = (val,ids,datas) => {
        const {workdate} = this.props;
        const {changeReplaceDatas} = this.props.blogMyBlog;
        changeReplaceDatas([])
        let vid =  "#shareFirstDiv_"+workdate;
        jQuery(vid).css("display","none")
        if(ids!=undefined&&ids!=''){
            this.setState({viewShareType:val+"",shareValue:ids,sreplaceDatas:datas})
        }else if(ids!=undefined&&ids==''){
            this.setState({viewShareType:1+""})
        }else {
            this.setState({viewShareType:val+""})
        }

    }


    clearStatusEcme = () => {
      this.setState({ecmeTemplateid:""})
    }

  render() {
    let { status,ecmeTemplateid} = this.state,
      { weiboCKEditorConfig,workdate,blogType,hasSubmited,defaultTemplate} = this.props;

    let {replaceDatas} = this.props.blogMyBlog;


    if(this.state.sreplaceDatas.length!=0){
        replaceDatas = this.state.sreplaceDatas;
    }

    let shareidd = "shareFirstDiv_"+workdate;



     if(ecmeTemplateid){
         return <WeiboEcmeEdit ecId={`${this && this.props && this.props.ecId || ''}_WeiboEcmeEdit@fvf7su`}
             workdate={workdate}
             blogType={blogType}
             hasSubmited={hasSubmited}
             clearStatusEcme={this.clearStatusEcme}
             defaultTemplate={defaultTemplate}
             weiboCKEditorConfig={weiboCKEditorConfig}
             ecmeTemplateid={ecmeTemplateid}
         />
     }

    //暂时接入过来 zxt
    let bottomBarConfig = [];
      if(!(window.location.href.indexOf("/user/")>0)) {
           bottomBarConfig.push({
                name: 'Component',
                show: <div className="wea-cb-item" onClick={this.blognottt}>
                    <span className='wea-cbi-icon icon-coms02-Send-it-to-Weibo'/>
                    <span className="wea-cbi-text">{getLabel(33305,'便签')}</span>
                </div>
            })
        }


      let uploadUrl = '';
    weiboCKEditorConfig && weiboCKEditorConfig.map(cg => {
      cg.name === 'selects' && bottomBarConfig.push({
        name: 'Component',
        show: <Mood ecId={`${this && this.props && this.props.ecId || ''}_Mood@pch91s@blogmood`} onSelect={mood => this.setState({mood})}/>
      })
	  
	  
       
	  
      cg.name === 'dialogs' && cg.items.map(item => {
        let obj = {
          isBlog: true,
          name: 'Browser',
          show: <div className="wea-cb-item">
            <span className={`wea-cbi-icon ${mirror[item].icon}`}/>
            <span className="wea-cbi-text">{mirror[item].nameFunc()}</span>
          </div>,
          type: mirror[item].type,
          title: mirror[item].nameFunc(),
          isSingle: item === 'Templet',
        };
        if (item === 'Templet') obj.onToolsChange = this.onTempletChange
        bottomBarConfig.push(obj);
      })
      cg.name === 'uploads' && cg.items.map(item => {
       
        bottomBarConfig.push({
          isBlog: true,
          name: 'Upload',
          show: <div className="wea-cb-item">
            <span className='wea-cbi-icon icon-blog-Enclosure'/>
            <span className="wea-cbi-text">{getLabel(156, "附件")}</span>
          </div>,
          uploadId: 'webo_edit',
          uploadUrl: "/api/doc/upload/uploadFile2Doc?"+"category="+item.Attachment.position,
          category: item.Attachment.position,
          maxUploadSize: item.Attachment.maxSize,
          style: {display: "inline-block"}
        })
          uploadUrl = "/api/doc/upload/uploadFile2Doc?"+"category="+item.Attachment.position;
      })
    })

      const {viewShareType,showBdShare} = this.state;


      let bd1Color = {'background-color':"white"};
      let bd2Color = {'background-color':"white"};
      let bd3Color = {'background-color':"white"};
      let bd4Color = {'background-color':"white","border-bottom":"1px solid #d7d7d7"};


      let repalceDatas3 = [];
      let repalceDatas4 = [];


      let hideStyle={width: 25,left: -12}

      let viewShare = getLabel(2161,'公开') ;
      if(viewShareType=='1'){
          bd1Color = {'background-color':"#ecf7fe"};
      }else if(viewShareType=='2'){
          viewShare = getLabel(83281,'私密') ;
          bd2Color = {'background-color':"#ecf7fe"};
      }else if(viewShareType=='3'){
          viewShare = getLabel(521692,'谁可以看') ;
          repalceDatas3 = replaceDatas;
          hideStyle={width: 50,left: -37}
          bd3Color = {'background-color':"#ecf7fe"};
      }else if(viewShareType=='4'){
          viewShare = getLabel(525176,'不给谁看') ;
          hideStyle={width: 50,left: -37}
          repalceDatas4 = replaceDatas;
          bd4Color = {'background-color':"#ecf7fe","border-bottom":"1px solid #d7d7d7"};
      }


     let bdStyle ={position: "relative",display:'none'};

      if(showBdShare==1){
          bdStyle ={position: "relative"};
      }


     const styleWeaHelpfulTip = {'margin-left': '10px', 'top': '2px', 'position': 'relative'};
     const styleSItitle = {"font-size":"14px"};
     const styleSIInfo = {'color':"#838181","font-size":"12px"};
     const postionRe = {position: "relative"};
     const vishide = {"visibility": "hidden"};
     const shareButtonTitleSty = {"font-size": "xx-small", "color":'#989a9c','margin-left':'10px'};

    let bottomBarRight = undefined;
    let extentsConfig = [];
    let {disabled} = this.props.blogMyBlog;
    if (status === 'ready') {
      bottomBarRight = {
        width: showBdShare==1?305:210,
        Component: (
            <div>
                <span className="wea-rich-text-toolbar-bottom-item" style={bdStyle}>
                   <div className="shareButtonTitle"  title={viewShare} style={hideStyle}>{viewShare}</div> <span className='icon-coms-down' onClick={this.changeShowViewShare} style={shareButtonTitleSty}>
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@bk7m73`}
                    width =  {260} //如果要自定义宽度，在这里设置
                    title={getLabel(525177,'微博没有真正意义上的"私密",上级和后端指定共享人为固定共享,不可修改."谁可以看"和"不给谁看"均为排除固定共享之后的筛选.') }
                    isCenter={true}
                    style={styleWeaHelpfulTip}
                    placement = 'bottom'
                    /></span>
                     <div className='viewShareAll'  id={shareidd}>
                         <div className='viewshareitem'  style={bd1Color} onClick={() => this.changeviewShareType(1)}>
                             <div className='viewshareitemicon'>
                               {viewShareType=='1'?<i className="icon-coms-Upload-successfully-o"/>:<i className="icon-coms-Upload-successfully-o" style={vishide}/>}
                             </div>
                              <div className='viewshareiteminfo'>
                                  <div className='viewshareitemtitle' style={styleSItitle}>{getLabel(2161,'公开') }</div>
                                  <div className='viewshareitemtitleinfo' style={styleSIInfo}>{getLabel(525178,'所有共享人可见') }</div>
                              </div>
                         </div>
              <div className='viewshareitem' style={bd2Color}  onClick={() => this.changeviewShareType(2)}>
                   <div className='viewshareitemicon'>
                       {viewShareType=='2'?<i className="icon-coms-Upload-successfully-o"/>:<i className="icon-coms-Upload-successfully-o" style={vishide}/>}
                   </div>
                              <div className='viewshareiteminfo'>
                                  <div className='viewshareitemtitle' style={styleSItitle}>{getLabel(83281,'私密') }</div>
                                  <div className='viewshareitemtitleinfo' style={styleSIInfo}>{getLabel(525179,'仅自己和固定共享人可见') }</div>
                              </div>
              </div>
              <div className='viewshareitem' style={bd3Color} >
                  <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@zum6ul`}
                    type="17"
                              title={getLabel(521692,'谁可以看')}
                              icon="icon-coms-blog"
                    browserModalProps ={{parentClassName:"viewShareDialog"}}
                    textDecoration={true}
                    dataParams={{
                                  bdShare:"1"
                              }}
                    completeParams={{
                                  bdShare:"1"
                              }}
                    conditionDataParams={{
                                  bdShare:"1"
                              }}
                      viewAttr={3}
                      inputStyle={{ width: 232 }}
                      onChange={(ids, names, datas) =>
                      {
                      this.changeviewShareTypeDis(3,ids,datas)
                      }}
                              replaceDatas={repalceDatas3}
                      customized={true}
                      isSingle={false}
                  >
                    <div className='viewshareitemicon'>
                        {viewShareType=='3'?<i className="icon-coms-Upload-successfully-o"/>:<i className="icon-coms-Upload-successfully-o" style={vishide}/>}
                    </div>
                    <div className='viewshareiteminfobrw'>
                       <div className='viewshareitemtitle' style={styleSItitle}>{getLabel(521692,'谁可以看') }</div>
                       <div className='viewshareitemtitleinfo' style={styleSIInfo}>{getLabel(525180,'指定共享人可见') }</div>
                    </div>
                  </WeaBrowser>
              </div>
              <div className='viewshareitem' style={bd4Color}  >
                  <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@o9xvo2`}
                  type="17"
                              title={getLabel(525176,'不给谁看')}
                              icon="icon-coms-blog"
                     textDecoration={true}
                              browserModalProps ={{parentClassName:"viewShareDialog"}}
                     dataParams={{
                                  bdShare:"1"
                                }}
                  completeParams={{
                                  bdShare:"1"
                                  }}
                  conditionDataParams={{
                                  bdShare:"1"
                              }}
                      viewAttr={3}
                      inputStyle={{ width: 232 }}
                      onChange={(ids, names, datas) =>
                      {
                          this.changeviewShareTypeDis(4,ids,datas)
                      }}
                              replaceDatas={repalceDatas4}
                      customized={true}
                      isSingle={false}
                  >
                         <div className='viewshareitemicon' >
                             {viewShareType=='4'?<i className="icon-coms-Upload-successfully-o"/>:<i className="icon-coms-Upload-successfully-o" style={vishide}/>}
                         </div>
                            <div className='viewshareiteminfobrw'>
                               <div className='viewshareitemtitle' style={styleSItitle}>{getLabel(525176,'不给谁看') }</div>
                               <div className='viewshareitemtitleinfo' style={styleSIInfo}>{getLabel(525181,'指定共享人不可见') }</div>
                            </div>
                  </WeaBrowser>
              </div>
          </div>
                 </span>
                <span className="wea-rich-text-toolbar-bottom-item" style={postionRe}>
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@m12f6s`} disabled={disabled}  onClick={this.saveBlog}>
                  <span>{getLabel(384355,'存草稿') }</span>
                </Button>
                 </span>
              <span className="wea-rich-text-toolbar-bottom-item" style={postionRe}>
					<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ih9rh6`} disabled={disabled} type="primary" onClick={this.publishWeiboPermission}>
						<span className="icon-coms-Release"/>&nbsp;&nbsp;<span>{getLabel(114, "发布")}</span>
					</Button>
				</span>
            </div>
        )
      };

        extentsConfig = [{
          name: "At",
          request: {
                url:"/api/blog/at/getAtAllList",
                type:"GET",
                params: {

              }
            }
        }];

        if(this.refs[this.CKE_ID]){
            if(this.refs[this.CKE_ID].getData()!=""){
                this.refs[this.CKE_ID].initAutoAt();
            }
        }
    }


    let WeaRichTextValue = '';

    if(this.props.ecmeDefaultTemplate){
        WeaRichTextValue=this.props.ecmeDefaultTemplate;
    }
      if(this.state.richValue.length>0){
          WeaRichTextValue=this.state.richValue;
      }




    return (
      <div className='wea-ckeditor-import-ecCom'>
        <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@yz0z55`}
          id={this.CKE_ID}
          ref={this.CKE_ID}
          ls={false}
          value={WeaRichTextValue}
          ckConfig={{
            toolbar: [
              {name: 'document', items: ['Source']},
              {
                name: 'paragraph',
                items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList']
              },
              {name: 'styles', items: ['Format', 'Font', 'FontSize']},
              {name: 'colors', items: ['TextColor']},
              {name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', "-","CopyFormatting","RemoveFormat"]},
			  {name: 'insert', items: ['Image', 'Table', 'Smiley']},
			  { name: 'tools', items: [ 'Maximize' ] }
            ],
            extraPlugins: 'autogrow',
            height: 150,
            autoGrow_minHeight: 150,
            autoGrow_maxHeight: 600,
            removePlugins: 'resize',
            uploadUrl: '/api/doc/upload/uploadFile',
          }}
          extentsConfig={extentsConfig}
          bottomBarConfig={bottomBarConfig}
          bottomBarRight={bottomBarRight}
          onStatusChange={this.onStausChange}
          onToolsChange={Util.transfStr}
        />

      </div>

    )
  }



    //处理模板复制多余内容镶嵌
    filterRichTextValue = (richValue) => {
        try {
            return  jQuery(richValue).find('.reportItem:last').html();
        } catch(e) {
            console.log(e);
        }
    }


    onTempletChange(name, ids, list, type) {

        if(list[0]&&list[0].contentType==1){
            this.setState({ecmeTemplateid:list[0].id})
        }else{
            let {saveWeaRichTextValue} = this.props.blogMyBlog

            let {richValue} = this.state;

            Util.templetChange(richValue, v => {
                this.setState({richValue: v});
                saveWeaRichTextValue && saveWeaRichTextValue({[`wea_rich_text_ls_${this.CKE_ID}`]: v}, false)
            }, name, ids, list, type)
        }


  }

//  <WeaCkEditor
//      id={this.CKE_ID}
//      ref={this.CKE_ID}
//      onReady={this.onReady}
//      content={(!hasSubmited && defaultTemplate.tempContent ? defaultTemplate.tempContent : "")}
//      type="blog"
//      config={{
//          extraPlugins: 'autogrow',
//          height:200,
//          autoGrow_minHeight: 200,
//          autoGrow_maxHeight: 600,
//          //autoGrow_bottomSpace: 50,
//          removePlugins: 'resize'
//      }}
//      configBar={weiboCKEditorConfig}
//      // onBlur={() => {
//      //     this.refs[this.CKE_ID] && this.refs[this.CKE_ID].CleanEditor()
//      // }}
//  />

  onAuthType = (authType) => {
    this.setState({authType: authType})
  }

  onAuthRange = (authRange) => {
    this.setState({authRange: authRange})
  }


  
  publishWeiboPermission = () => {

    let {editWeibo, getBasicInfo,setDisabled,getIsOneSubmitInfo,setIsNoTip} = this.props.blogMyBlog;
    let {authType, authRange, mood, richValue} = this.state,
      {blogType, user, workdate} = this.props
    let _this = this;
    getIsOneSubmitInfo(result => {
      if (result.oneSubmit == "1" && result.submitCount>0) {
          message.warning(getLabel('521404',"您已发布过今天的微博，不能再发布，已为您保存草稿。"));
          setIsNoTip(true);
          this.saveBlog();
      }else{
        if(result.oneSubmit == "1"&& result.submitCount==0){
          confirm({//
            title: getLabel('131329',"信息确认"),
            content: getLabel('521430',"当日微博仅能提交一次，确定要发布吗？"),
            onOk() {
              _this.publishWeibo();
            },
            onCancel() {},
          });
        }else{
          _this.publishWeibo();
        }
      }
    })
  }
  publishWeibo = () => {
    let {editWeibo, getBasicInfo,setDisabled,getIsOneSubmitInfo,setIsNoTip,changeReplaceDatas} = this.props.blogMyBlog;
    let {authType, authRange, mood, richValue,viewShareType,shareValue} = this.state,
      {blogType, user, workdate} = this.props
    let ckref = this.refs[this.CKE_ID];
    if (this.refs[this.CKE_ID] && this.refs[this.CKE_ID].wrappedInstance) {
      ckref = this.refs[this.CKE_ID].wrappedInstance;
    }
    if (!(ckref && ckref.checkMode())) {
      message.error(getLabel('384536', "不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式"));
      return;
    }

      let value = ckref.getData();
      //console.info("publishWeibo", value);
      richValue = value;
      let testV = value;
      testV = testV.replace(new RegExp(/(\n)/g),'')
      testV = testV.replace(/<p>|<\/p>/gi,"");

      if(testV==""){
          richValue = testV;
      }

      this.setState({richValue: "", isFirstIn: false});
      //let {saveWeaRichTextValue} = this.props.blogMyBlog
      //saveWeaRichTextValue && saveWeaRichTextValue({[`wea_rich_text_ls_${this.CKE_ID}`]: value}, false)

    typeof setDisabled === 'function' && setDisabled(true);
    localStorage.removeItem(`wea_rich_text_ls_${this.CKE_ID}`);


      let filterValue  = this.filterRichTextValue(richValue);

      if(filterValue){
          richValue = filterValue;
      }

    editWeibo(
      {
        appItemId: mood || "1",
        comefrom: ComeFrom.pc,
        content: richValue,
        workdate: "",
        shareType:viewShareType,
        shareValue:shareValue,
        atChooseId: this.refs[this.CKE_ID].getChooseId(),
          fromTag: 2
      },
      {
        type: blogType,
        workdate: workdate
      },
      result => {

          if(this.props.clearStatus){
              this.props.clearStatus();
          }

          this.setState({viewShareType:'1',shareValue:''})
        if (result.status == "1") {
          getBasicInfo()
            changeReplaceDatas([])
          if (this.refs[this.CKE_ID] && this.refs[this.CKE_ID].wrappedInstance) {
            this.refs[this.CKE_ID].wrappedInstance.setData('');

          } else {
            this.refs[this.CKE_ID].setData('');

          }
            message.destroy();
            message.success(getLabel('83885',"操作成功！"));
          // this.refs[this.CKE_ID].pushAtMessage(() => {
          //   console.log('消息发送成功后的回调');
          // });

        }
      }
    )

  }
  onReady = () => {
    this.setState({editing: true, richValue: ''})
  }
}

export default WeiboEdit